package com.begye.smartloan.apptest.renzheng.document

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.Size
import android.view.View
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.core.resolutionselector.ResolutionSelector
import androidx.camera.core.resolutionselector.ResolutionStrategy
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.begye.smartloan.apptest.MyApplication
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.databinding.AtRenZhengDocumentCaptureBinding
import com.begye.smartloan.apptest.tool.addTouch
import com.util.utillib.util.imagecovert.ImageConvert
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog
import java.io.File


@SuppressLint("CustomSplashScreen")
class RenZhengDocumentCaptureActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    companion object {
        const val REQUEST_CODE_DOCUMENT_CAPTURE = 303
    }

    private lateinit var binding: AtRenZhengDocumentCaptureBinding

    private var imageCapture: ImageCapture? = null
    private lateinit var imageOutputPath: String

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 关联布局
        binding = AtRenZhengDocumentCaptureBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 设置全屏
        fullScreen()

        // 输出路径
        imageOutputPath = outFilePath()

        // 用到的控件
        val hotline = binding.navbarRight
        val back = binding.navbarLeft
        val navTitle = binding.navbarTitle

        val title = intent.getStringExtra("title") ?: getString(R.string.fill_text_49)
        navTitle.text = title

        // 点击确定拍照
        binding.takePicture.setOnClickListener {
            val imageCapture = imageCapture ?: return@setOnClickListener
            val outputOptions = ImageCapture.OutputFileOptions
                .Builder(File(imageOutputPath))
                .build()

            imageCapture.takePicture(
                outputOptions,
                ContextCompat.getMainExecutor(this),
                object : ImageCapture.OnImageSavedCallback {
                    override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                        try {
                            //压缩图片
                            ImageConvert.startConvertImage(
                                this@RenZhengDocumentCaptureActivity,
                                File(imageOutputPath)
                            ) { localPath, thumpImg ->
                                //重置UI
                                if (thumpImg != null) {
                                    imageOutputPath = localPath.toString()

                                    binding.imageResult.visibility = View.VISIBLE
                                    binding.imageResult.setImageBitmap(thumpImg)

                                    binding.takePicture.visibility = View.GONE
                                    binding.resultActionBg.visibility = View.VISIBLE
                                }
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }

                    override fun onError(exception: ImageCaptureException) {
                        println("Photo capture failed: ${exception.message}")
                    }
                }
            )

            // update action buttons display
            binding.resultActionBg.visibility = View.VISIBLE
            binding.takePicture.visibility = View.GONE
        }

        // 点击重拍
        binding.retake.setOnClickListener {
            binding.imageResult.setImageBitmap(null)
            binding.imageResult.visibility = View.GONE
            binding.resultActionBg.visibility = View.GONE
            binding.takePicture.visibility = View.VISIBLE

//            hitPoint("PIC_RETAKE")
        }

        // 点击使用该图
        binding.usePicture.setOnClickListener {
//            hitPoint("PIC_USE_PIC")
            runOnUiThread {
                val type = intent.getStringExtra("type") ?: ""
                val resultIntent = Intent()
                resultIntent.putExtra("path", imageOutputPath)
                resultIntent.putExtra("type", type)
                setResult(Activity.RESULT_OK, resultIntent)
                finish()
            }
        }

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
//            HotlineGhanaDialog().showNow(supportFragmentManager, "hotline")
//            hitPoint("SHOW_HOTLINE")
        }

        // 点击返回
        back.setOnClickListener {
            finish()
        }

        // 请求权限
        if (!askCameraPermission()) {
            openCameraPreview()
        }
    }

    /**
     * 请求相机权限
     */
    private fun askCameraPermission(): Boolean {
        if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(
                this,
                android.Manifest.permission.CAMERA
            )
        ) {
            return false
        }
        // 未同意权限
        EasyPermissions.requestPermissions(
            this,
            getString(R.string.disclosure_text_11),
            REQUEST_CODE_DOCUMENT_CAPTURE,
            android.Manifest.permission.CAMERA
        )
        return true
    }

    /**
     * 启动相机预览
     */
    private fun openCameraPreview() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener({
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .build()
                .also {
                    it.setSurfaceProvider(binding.previewView.surfaceProvider)
                }

            //设置预览尺寸
            val screenWidth = resources.displayMetrics.widthPixels// binding.previewView.width
            val screenHeight = resources.displayMetrics.heightPixels//binding.previewView.height
            val resolutionStrategy = ResolutionStrategy(
                Size(screenHeight, screenWidth),
                ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER
            )
            val resolutionSelector = ResolutionSelector.Builder()
                .setResolutionStrategy(resolutionStrategy)
                .build()

            imageCapture = ImageCapture.Builder()
                .setResolutionSelector(resolutionSelector)
                .build()

            val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 输出路径
     */
    private fun outFilePath(): String {
        val imgDir = "${filesDir}${File.separator}${MyApplication.product.uppercase()}_TEMP_PICS"
        val dirFile = File(imgDir)
        if (!dirFile.exists()) {
            dirFile.mkdirs()
        }

        return "$imgDir${File.separator}${System.currentTimeMillis()}.jpg"
    }

    // ------> EasyPermissions <------
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        askCameraPermission()
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        openCameraPreview()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            askCameraPermission()
        }
    }

    /**
     * 设置全屏
     */
    private fun fullScreen() {
        try {
            // 设置全屏
            window.decorView.systemUiVisibility =
                (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                window.statusBarColor = Color.TRANSPARENT
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                window.decorView.systemUiVisibility =
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            }

        }catch (e:Exception){
            //
        }
    }

    override fun onResume() {
        super.onResume()
        addTouch(type = this.javaClass.simpleName, isOpen = true)
    }

    override fun onPause() {
        super.onPause()
        addTouch(type = this.javaClass.simpleName, isComplete = true)
    }
}